package com.boomsecret.juc.tools;

import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;

/**
 * @author wangjinliang on 2019/1/23.
 */
public class ExchangerDemo {

    public static void main(String[] args) {
        Exchanger<String> exchanger = new Exchanger<>();
        Thread threadA = new Producer(exchanger);
        Thread threadB = new Consumer(exchanger);
        threadA.start();
        threadB.start();

        try {
            threadA.join();
            threadB.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("main end");
    }

    public static class Producer extends Thread {
        private Exchanger<String> exchanger;
        private String buffer;

        public Producer(Exchanger<String> exchanger) {
            this.exchanger = exchanger;
        }

        @Override
        public void run() {
            for (int index = 0; index < 10; index ++) {
                try {
                    TimeUnit.SECONDS.sleep(2);
                    buffer = "data" + index;
                    buffer = exchanger.exchange(buffer);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static class Consumer extends Thread {
        private Exchanger<String> exchanger;
        private String buffer;

        public Consumer(Exchanger<String> exchanger) {
            this.exchanger = exchanger;
        }

        @Override
        public void run() {
            for (int index = 0; index < 10; index ++) {
                try {
                    buffer = exchanger.exchange(buffer);
                    System.out.println("Consumer data -->" + buffer);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                buffer = "";
            }
        }
    }
}
